<template>
    <div class="role">
        <div class="top">
            <el-form :inline="true">
                <el-form-item label="职位搜索">
                    <el-input placeholder="请你输入搜索职位关键字" v-model="keywords"></el-input>
                </el-form-item>
            </el-form>
            <div class="operate">
                <el-button
                    type="primary"
                    icon="search"
                    @click="handleSearch"
                    :disabled="keywords.length === 0"
                >
                    搜索
                </el-button>
                <el-button type="primary" icon="refresh" @click="handleReset">重置</el-button>
            </div>
        </div>
        <div class="content">
            <el-button type="primary" icon="plus" @click="handleAddRole">添加职位</el-button>

            <el-table border class="table" :data="records" show-overflow-tooltip>
                <el-table-column label="#" align="center" type="index" />
                <el-table-column label="ID" align="center" prop="id" />
                <el-table-column label="职位名称" align="center" prop="roleName" />
                <el-table-column label="创建时间" align="center" prop="createTime" />
                <el-table-column label="更新时间" align="center" prop="updateTime" />
                <el-table-column label="操作" align="center" width="300">
                    <template #default="{ row }">
                        <el-button
                            size="small"
                            type="primary"
                            icon="user"
                            @click="handleSetPermission(row)"
                        >
                            分配权限
                        </el-button>
                        <el-button
                            size="small"
                            type="primary"
                            icon="edit"
                            @click="handleEditRole(row)"
                        >
                            编辑
                        </el-button>
                        <el-popconfirm
                            width="250px"
                            :title="`您确定要删除职位${row.roleName}吗？`"
                            @confirm="handleRemoveRole(row)"
                        >
                            <template #reference>
                                <el-button size="small" type="danger" icon="delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                v-model:current-page="page"
                v-model:page-size="size"
                :page-sizes="[3, 5, 7, 9]"
                background
                layout="prev, pager, next, jumper,->,sizes,total"
                :total="total"
                @current-change="getRoleList"
                @size-change="handleSizeChange"
            />

            <el-dialog
                v-model="dialogFormVisible"
                :title="saveRoleData.id ? '更新职位' : '添加职位'"
                width="500"
            >
                <el-form :model="saveRoleData" ref="roleFormRef" :rules="rules">
                    <el-form-item label="职位名称" prop="roleName">
                        <el-input autocomplete="off" v-model="saveRoleData.roleName" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleSaveRoleConfirm">确定</el-button>
                    </div>
                </template>
            </el-dialog>

            <el-drawer direction="rtl" v-model="savePermissionDrawer">
                <template #header>
                    <h4>分配菜单与按钮的权限</h4>
                </template>
                <template #default>
                    <div>
                        <el-tree
                            style="max-width: 600px"
                            :data="permissionData"
                            show-checkbox
                            node-key="id"
                            :default-checked-keys="hasPermission"
                            :props="defaultProps"
                            default-expand-all
                            ref="permissionTreeRef"
                        />
                    </div>
                </template>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="savePermissionDrawer = false">取消</el-button>
                        <el-button type="primary" @click="handleSavePermission">确定</el-button>
                    </div>
                </template>
            </el-drawer>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { useSettingStore } from '@/store/modules/setting'
import { ElMessage } from 'element-plus'
import {
    reqAllRoleList,
    reqAddOrUpdateRole,
    reqRemoveRole,
    reqAllMenuList,
    reqSetPermisstion,
} from '@/api/acl/role'

const page = ref<number>(1)
const size = ref<number>(3)
const total = ref<number>(0)
const records = ref<any[]>([])

const keywords = ref<string>('')

const settingStore = useSettingStore()

const getRoleList = async (p: number = 1) => {
    page.value = p
    let result: any = await reqAllRoleList(page.value, size.value, keywords.value)
    if (result.code === 200) {
        records.value = result.data.records
        total.value = result.data.total
    }
}

const handleSizeChange = () => {
    getRoleList()
}

onMounted(() => {
    getRoleList()
})

const handleSearch = () => {
    getRoleList()
    keywords.value = ''
}

const handleReset = () => {
    settingStore.refreshPage = !settingStore.refreshPage
}

const saveRoleData = ref({
    id: 0,
    roleName: '',
})

const dialogFormVisible = ref<boolean>(false)

const rules = {
    roleName: [
        { required: true, message: '请输入职位名称', trigger: 'blur' },
        { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
    ],
}

const roleFormRef = ref()

const handleAddRole = () => {
    Object.assign(saveRoleData.value, {
        id: 0,
        roleName: '',
    })
    dialogFormVisible.value = true
    nextTick(() => {
        roleFormRef.value.clearValidate()
    })
}

const handleEditRole = (row: any) => {
    Object.assign(saveRoleData.value, row)
    dialogFormVisible.value = true
    nextTick(() => {
        roleFormRef.value.clearValidate()
    })
}

const handleSaveRoleConfirm = async () => {
    await roleFormRef.value.validate()

    let result: any = await reqAddOrUpdateRole(saveRoleData.value)
    if (result.code === 200) {
        const msg = saveRoleData.value.id ? '更新成功' : '添加成功'
        dialogFormVisible.value = false
        ElMessage.success(msg)
        getRoleList(saveRoleData.value.id ? page.value : 1)
    } else {
        const msg = saveRoleData.value.id ? '更新失败' : '添加失败'
        ElMessage.error(msg)
    }
}

const handleRemoveRole = async (row: any) => {
    let result: any = await reqRemoveRole(row.id)
    if (result.code === 200) {
        ElMessage.success('删除成功')
        getRoleList(records.value.length > 1 ? page.value : page.value - 1)
    } else {
        ElMessage.error('删除失败')
    }
}

const savePermissionDrawer = ref<boolean>(false)

const defaultProps = {
    children: 'children',
    label: 'name',
}

let permissionData: any[] = []

let hasPermission = ref<number[]>([])

const handleSetPermission = async (row: any) => {
    let result: any = await reqAllMenuList(row.id)
    if (result.code === 200) {
        permissionData = result.data

        savePermissionDrawer.value = true

        hasPermission.value = filterHasPermission(result.data, [])

        Object.assign(saveRoleData.value, row)
    }
}

const filterHasPermission = (data: any, hasPermiss: any) => {
    data.forEach((item: any) => {
        if (item.select && item.level === 4) {
            hasPermiss.push(item.id)
        }
        if (item.children && item.children.length > 0) {
            filterHasPermission(item.children, hasPermiss)
        }
    })

    return hasPermiss
}

const permissionTreeRef = ref()

const handleSavePermission = async () => {
    let checkedKeys = permissionTreeRef.value.getCheckedKeys()
    let halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()

    let allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]

    let result: any = await reqSetPermisstion(saveRoleData.value.id, allCheckedKeys)
    if (result.code === 200) {
        //抽屉关闭
        savePermissionDrawer.value = false
        //提示信息
        ElMessage({ type: 'success', message: '分配权限成功' })
        //页面刷新
        window.location.reload()
    }
}
</script>

<style lang="scss" scoped>
.role {
    .top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        border-bottom: 1px solid #e4e7ed;
    }

    .content {
        .table {
            margin: 20px 0;
        }
    }
}
</style>
